﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Text.RegularExpressions;

namespace SupplyChainManagement
{
    /// <summary>
    /// Form for editing a product's details
    /// </summary>
    public partial class ProdEditForm : Form
    {
        List<string> rawitemData;
        List<string> selectedItems = new List<string>();
        ProductForm prod;
        string toEdit;

        public string ProductID
        {
            get { return txtID.Text; }
        }

        public ProdEditForm(ProductForm prod, string toEdit)
        {
            this.prod = prod;
            InitializeComponent();
            rawitemData = new List<string>();
            this.toEdit = toEdit;
            LoadListBox();

        }

        //populate the listbox with the required data
        private void LoadListBox()
        {
            OdbcConnection dbMySQL = new OdbcConnection(MainForm.strConnect);
            
            try
            {
                //open database
                dbMySQL.Open();

                //get product's details
                OdbcCommand readcommand = dbMySQL.CreateCommand();
                readcommand.CommandText = "select * from product where pro_id='" + toEdit + "'";
                OdbcDataReader reader = readcommand.ExecuteReader();
                while (reader.Read())
                {
                    txtID.Text = toEdit;
                    txtPName.Text = reader.GetString(1);
                    txtAmount.Text = reader.GetString(2);
                    txtMax.Text = reader.GetString(3);
                    txtMin.Text = reader.GetString(4);
                }
                reader.Close();
                readcommand.Dispose();

                OdbcCommand sqlCommand = dbMySQL.CreateCommand();
                //assign the SQL command
                sqlCommand.CommandText = "select inv_name from inventory";

                //reader executes the select command
                OdbcDataReader sqlReader = sqlCommand.ExecuteReader();

                
                while (sqlReader.Read())
                {
                    rawitemData.Add(sqlReader.GetString(0));
                }

                //close readers and dispose the commands
                sqlReader.Close();
                sqlCommand.Dispose();
                rawItemListBox.Items.AddRange(rawitemData.ToArray());

                OdbcCommand rawItemSelect = dbMySQL.CreateCommand();
                //assign the SQL command
                rawItemSelect.CommandText = "select inv_name from contain where pro_id='" + 
                    toEdit + "'";

                
                OdbcDataReader rawItemReader = rawItemSelect.ExecuteReader();
                while (rawItemReader.Read())
                {
                    //loop through the list box, if the item is the same as the one in the list
                    //determine it as a selected item and set it as selected
                    for (int i = 0; i < rawItemListBox.Items.Count; i++)
                    {
                        if (rawItemReader.GetString(0) == rawItemListBox.Items[i].ToString())
                            rawItemListBox.SelectedItems.Add(rawItemListBox.Items[i]);
                    }
                }              
            }
            catch (OdbcException ex)
            {
                Console.WriteLine("Database error\n\n{0}", ex.ToString());
            }
            finally
            {
                if (dbMySQL != null) dbMySQL.Close();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            //error checking
            selectedItems.Clear();
            foreach (string s in rawItemListBox.SelectedItems)
            {
                selectedItems.Add(s.ToString());
            }
            if (string.IsNullOrEmpty(txtAmount.Text) || string.IsNullOrEmpty(txtPName.Text) ||
                string.IsNullOrEmpty(txtMin.Text) || string.IsNullOrEmpty(txtMax.Text))
                MessageBox.Show("Data is not complete");
            else if (selectedItems.Count == 0)
                MessageBox.Show("No raw item selected!");
            else if (!Regex.IsMatch(txtAmount.Text, @"^[0-9,-\.]+$") && !Regex.IsMatch(txtMin.Text, @"^[0-9,-\.]+$")
                && !Regex.IsMatch(txtMax.Text, @"^[0-9,-\.]+$"))
                MessageBox.Show("Data not valid!");
            else
            {
                ProductEditNext next = new ProductEditNext(selectedItems, this, prod);
                next.Show();
            }          
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
            prod.Enabled = true;
            prod.Activate();
        }
        
        /// <summary>
        /// To update the database
        /// </summary>
        public void SaveToDatabase()
        {
            OdbcConnection dbMySQL = new OdbcConnection(MainForm.strConnect);
            try
            {
                dbMySQL.Open();

                OdbcCommand sqlCommand = dbMySQL.CreateCommand();
                sqlCommand.CommandText = "update product set pro_name='" + txtPName.Text + "', pro_amount='" +
                    txtAmount.Text + "', pro_max='" + txtMax.Text + "', pro_min='" + txtMin.Text
                    + "' where pro_id='" + txtID.Text + "'";
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Dispose();
            }
            catch (OdbcException ex)
            {
                Console.WriteLine("Database error\n\n{0}", ex.ToString());
            }
            finally
            {
                if (dbMySQL != null) dbMySQL.Close();
            }
        }

        private void ProdEditForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            prod.Enabled = true;
            prod.Activate();
        }

    }
}
